
package electricity.controller;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import electricity.domain.SysUser;
import electricity.dto.UserDto;
import electricity.mapper.SysUserMapper;
import electricity.result.Result;
import electricity.service.LoginService;
import electricity.service.PermissionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/login")
@Tag(name ="登录相关接口")
@Slf4j
public class UserController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PermissionService permissionService;


    @PostMapping
    @Operation(summary = "用户登录")
    public Result login(@RequestBody UserDto userDto) {
        log.info("用户登录：{}", userDto);

        String token = loginService.login(userDto);
        return Result.success(token);
    }

    @GetMapping("/test")
    public String test() {
        List<SysUser> list = sysUserMapper.list();
        return list.toString();
    }

    @PostMapping("/loginTest")
    @Operation(summary = "用户登录测试")
    public Map<String, Object> login(@RequestBody Map<String, String> loginParam) {
        String username = loginParam.get("username");
        String password = loginParam.get("password");
//        log.info("用户登录：{}", loginParam);
        boolean result = loginService.login(username, password);
        Map<String, Object> response = new HashMap<>();
        if (result) {
            //获取权限
            SysUser sysUser = loginService.selectByUsername(username);
            List<String> permissionCodes = permissionService.getPermissionCodesByUserId(sysUser.getId());
            //存储权限
            if (permissionCodes != null && !permissionCodes.isEmpty()) {
                // 获取当前用户的会话对象
                SaSession session = StpUtil.getSession();
                // 存储权限列表（key 自定义，例如 "permissions"）
                session.set("permissions", permissionCodes);
            }

            response.put("code", 200);
            response.put("status", "success");
            response.put("message", "登录成功");
            response.put("satoken", StpUtil.getTokenValue());
            response.put("permissions", permissionCodes);
            response.put("userId", sysUser.getId());
        } else {
            response.put("code", 401);
            response.put("status", "fail");
            response.put("message", "用户名或密码错误");
        }
        return response;
    }
    //获取当前用户的权限
    @GetMapping("/currentUserPermissions")
    @Operation(summary = "获取当前用户的权限")
    public Map<String, Object> getCurrentUserPermissions() {
        Map<String, Object> response = new HashMap<>();
        try {

            StpUtil.checkLogin(); // 检查登录状态
            // 从会话中获取权限
            SaSession session = StpUtil.getSession();
            List<String> permissions = (List<String>) session.get("permissions");
            // 确保返回非空列表
            if (permissions == null) {
                permissions = Collections.emptyList();
            }

            response.put("code", 200);
            response.put("status", "success");
            response.put("permissions", permissions); // 返回权限码列表
        } catch (Exception e) {
            response.put("status", "fail");
            response.put("message", "获取权限失败：" + e.getMessage());
        }
        return response;
    }
    // 退出登录接口
    @PostMapping("/logout")
    @Operation(summary = "用户退出登录")
    public Map<String, Object> logout() {
        Map<String, Object> response = new HashMap<>();
        try {
            // 1. 调用 Sa-Token 的 logout 方法，清除当前用户的登录状态
            // 会自动删除当前用户的 satoken 会话信息
            StpUtil.logout();

            // 2. 返回成功响应
            response.put("code", 200);
            response.put("status", "success");
            response.put("message", "退出登录成功");
        } catch (Exception e) {
            response.put("status", "fail");
            response.put("message", "退出登录失败：" + e.getMessage());
        }
        return response;
    }

}
